package uk.co.caprica.vlcj.oop.util;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;

/**
 * Classpath utilities.
 */
public final class Classpath {

    /**
     * Get the application classpath.
     * 
     * @return classpath
     */
    public static String classpath() {
        try {
            StringBuilder sb = new StringBuilder(200);
            ClassLoader sysClassLoader = ClassLoader.getSystemClassLoader();
            URL[] urls = ((URLClassLoader)sysClassLoader).getURLs();
            for(URL url : urls) {
                // Add a path separator if not the first
                if(sb.length() > 0) {
                    sb.append(File.pathSeparatorChar);
                }
                // Add the current file to the class-path
                String file = url.getFile();
                if(file.endsWith("/")) {
                    sb.append(file.substring(0, file.length() - 1));
                }
                else {
                    sb.append(file);
                }
                // If the URL is a jar file, then check for a manifest class-path...
                if(file.endsWith(".jar")) {
                    JarFile jarFile = new JarFile(file, false);
                    Manifest manifest = jarFile.getManifest();
                    if(manifest != null) {
                        String cp = (String)manifest.getMainAttributes().get(Attributes.Name.CLASS_PATH);
                        if(cp != null) {
                            File relativeTo = new File(file).getParentFile();
                            String[] entries = cp.split(" ");
                            for(String entry : entries) {
                                sb.append(File.pathSeparatorChar);
                                sb.append(new File(relativeTo, entry).getCanonicalPath());
                            }
                        }
                        // FIXME is this supposed to be recursive???
                    }
                }
            }
            return sb.toString();
        }
        catch(IOException e) {
            throw new RuntimeException("Failed to determine application classpath", e);
        }
    }
}
